package com.frx.sort.bublesort;

import java.util.Arrays;

/**
 * Created with IDEA
 *
 * @author: xrf
 * @Date: 2019/10/21
 * @Time: 20:11
 */
public class TestOne {

    public static void main(String[] args){
        /*int[] a = {1,3,2,6,4,5};*/
        int[] a = {5,8,6,3,9,2,1,7};
        int[] b = {2,1,3,4,5,6,7,8};
        sort2(a);
        sort3(b);
        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.toString(b));
    }
    /**
     * 最基础版本的冒泡排序
     * */
    public static void sort(int[] arr){
        int tmp = 0;
        for (int i=0; i < arr.length;i++){
            for (int j = 0; j < arr.length-1-i;j++){
                if (arr[j] > arr[j+1]){
                    tmp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = tmp;
                }
            }
        }
    }
    /**
     * 冒泡排序优化 1 设置变量在数据有序时退出遍历
     * */
    public static void sort2(int[] arr){
        int tmp = 0;

        for (int i=0;i<arr.length;i++){
            boolean isSort = true;
            for (int j=0; j < arr.length -1-i;j++){
                if (arr[j] > arr[j+1]){
                    tmp = arr[j+1];
                    arr[j+1] = arr[j];
                    arr[j] = tmp;
                    isSort = false;
                }
            }
            if (isSort){
                break;
            }
        }
    }

    public static void sort3(int[] arr){
        int tmp = 0;
        boolean isSort = true;
        int sortBorder = arr.length -1;
        int lastChangeIndex = 0;
        for (int i=0;i<arr.length;i++){

            for (int j=0;j<sortBorder;j++){
                if (arr[j] > arr[j+1]){
                    tmp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = tmp;
                    isSort = false;
                    lastChangeIndex = j;
                }

            }
            sortBorder = lastChangeIndex;
            if (isSort){
                break;
            }
        }
    }
}
